/*
 * Copyright (c) Yongjie.Ye <sockyjam@gmail.com>
 * All rights reserved.
 *
 */




#include "libdisperse.h"

#include "liblog.h"

static struct event_base *main_base;
static struct event main_event;

static int main_socket(int port);
static void main_conn_handler(int fd, short event_type, void *arg);


void disperse_init(void)
{


    main_base = event_init();


    event_base_loop(main_base, 0);
    
    return ;
}

static int main_socket(int port)
{
    int msfd; // main socket fd
    char port_buf[NI_MAXSERV];
    int sfd_flags;
    struct sockaddr_in servaddr;

    msfd = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == msfd)
    {
        perror("fail to open main socket");
        return -1;
    }

    /* set socket to non-block mode */
    if ((sfd_flags = fcntl(sfd, F_GETFL, 0)) < 0 || \
                fcntl(sfd, F_SETFL, sfd_flags | O_NONBLOCK) < 0)
    {
        perror("setting O_NONBLOCK");
        close(msfd);
        return -1;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(DEFAULT_DISPERSE_PORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(-1 == bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
    {
        perror("bind");
        close(msfd);
        return -1;
    }

    if (-1 == listen(msfd, MAX_LISTEN))
    {
        perror("listen");
        close(msfd);
        return -1;
    }
    
    event_set(&main_event, msfd, EV_READ | EV_PERSIST, main_conn_handler, (void *)NULL);
    event_base_set(main_base, &main_event);
    if (-1 == event_add(&main_event, 0))
    {
        perror("event add");
        close(msfd);
        return -1;
    }
    
    
    
    return 0;
}


static void main_conn_handler(int msfd, short event_type, void *arg)
{
    int sfd;
    struct event *new_conn_event;
        
    struct sockaddr cliaddr;

    sfd = accept(msfd, &cliaddr, sizeof(cliaddr));
    if (-1 == sfd)
    {
        perror("accept");
        return ;
    }

    new_conn_event = malloc();

    event_set(new_conn_event, sfd, EV_READ | EV_PERSIST, , (void *)NULL);

    
    return ;
}


